Skip to main content

Overview

The CLIP class implements the core CLIP (Contrastive Language-Image Pre-Training) model architecture. It combines a vision encoder and text encoder to learn aligned multimodal representations through contrastive learning. The model outputs normalized image and text features that can be compared in a shared embedding space using cosine similarity.

Class Definition

Initialization Parameters

int
required
Dimensionality of the joint embedding space for image and text features.
CLIPVisionCfg
required
Configuration object for the vision encoder. Controls architecture (ViT, ResNet, or timm model), layer depth, width, and attention settings.
CLIPTextCfg
required
Configuration object for the text encoder. Specifies transformer architecture, vocabulary size, context length, and pooling strategy.
bool
default:"False"
Use QuickGELU activation (as in original OpenAI models) instead of standard GELU. QuickGELU is less memory efficient but maintains compatibility with OpenAI checkpoints.
float
default:"np.log(1 / 0.07)"
Initial value for the learned temperature parameter (logit scale) that controls the sharpness of the similarity distribution.
Optional[float]
default:"None"
Optional learnable bias term added to logits. When None, no bias is used.
bool
default:"False"
If True, logit_scale has shape [1] instead of []. Some training frameworks require explicit dimensions.
Optional[torch.dtype]
default:"None"
Precision for model computations (e.g., torch.float16, torch.bfloat16). Used for mixed precision training.
bool
default:"False"
If True, forward() returns a dictionary with named outputs. If False, returns a tuple.

Attributes

  • visual: Vision encoder module (VisionTransformer, ModifiedResNet, or TimmModel)
  • transformer: Text transformer encoder
  • token_embedding: Text token embedding layer
  • positional_embedding: Learned positional embeddings for text
  • ln_final: Final layer normalization for text features
  • text_projection: Projection matrix from text features to joint embedding space
  • logit_scale: Learned temperature parameter (exponential of stored value)
  • logit_bias: Optional learned bias (if init_logit_bias is not None)
  • context_length: Maximum text sequence length
  • vocab_size: Size of text vocabulary

Key Methods

encode_image

Encodes images into the joint embedding space. Parameters:
  • image: Image tensor of shape (batch_size, channels, height, width)
  • normalize: If True, L2-normalizes the output features
Returns: Image features of shape (batch_size, embed_dim)

encode_text

Encodes tokenized text into the joint embedding space. Parameters:
  • text: Tokenized text tensor of shape (batch_size, context_length)
  • normalize: If True, L2-normalizes the output features
Returns: Text features of shape (batch_size, embed_dim)

get_logits

Computes similarity logits between image and text features. Parameters:
  • image: Image tensor
  • text: Tokenized text tensor
Returns: Tuple of (image_logits, text_logits) representing similarity scores scaled by temperature

forward

Forward pass through the model. Parameters:
  • image: Optional image tensor
  • text: Optional tokenized text tensor
Returns:
  • If output_dict=True: Dictionary with keys image_features, text_features, logit_scale, and optionally logit_bias
  • If output_dict=False: Tuple of (image_features, text_features, logit_scale) or (image_features, text_features, logit_scale, logit_bias)

forward_intermediates

Forward pass that returns intermediate layer features. Useful for feature extraction, analysis, and distillation. Returns: Dictionary with intermediate features, final features, and optionally logits

lock_image_tower

Freezes the image encoder for efficient fine-tuning (LiT-style training). Parameters:
  • unlocked_groups: Number of layer groups to keep trainable (from the end)
  • freeze_bn_stats: If True, freezes batch normalization statistics

lock_text_tower

Freezes the text encoder for efficient fine-tuning. Parameters:
  • unlocked_layers: Number of transformer layers to keep trainable (from the end)
  • freeze_layer_norm: If True, freezes layer normalization parameters

set_grad_checkpointing

Enables or disables gradient checkpointing to reduce memory usage during training at the cost of computation.

Usage Example

Fine-tuning Example

  • CustomTextCLIP - Variant with separately built text tower
  • CoCa - Contrastive Captioner model
  • ClipLoss - Contrastive loss function for CLIP